﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc4Learn.Filters;
using Mvc4Learn.Models;
using Mvc4Learn.Models.Enum;
using Mvc4Learn.Models.ViewModels;

namespace Mvc4Learn.Controllers
{
//    [Authorize(Roles="Admin")]
    [ManagerOnly(Roles = "Admin,PowerManager")]
    public partial class MusicStoreController : Controller
    {
        private MusicStoreContext db = new MusicStoreContext();

        //
        // GET: /MusicStore/

        public ActionResult Index()
        {
            var albums = db.Albums.Include(a => a.Genre).Include(a => a.Artist);
            return View(albums.ToList());
        }

        //
        // GET: /MusicStore/Details/5

        public ActionResult Details(int id = 0)
        {
            //            db.Albums.Load();

            Album album = db.Albums.Find(id);

            if (album == null)
            {
                return HttpNotFound();
            }

            //关闭了Lazy Loading后的后果
            Artist artist = db.Artists.Find(album.ArtistId);
            album.Artist = artist;

            Genre genre = db.Genres.Find(album.GenreId);
            album.Genre = genre;

            return View(album);
        }

        //
        // GET: /MusicStore/Create

        public ActionResult Create()
        {
            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name");
            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name");
            return View();
        }

        //
        // POST: /MusicStore/Create

        [HttpPost]
        public ActionResult Create(Album album)
        {
            if (ModelState.IsValid)
            {
                db.Albums.Add(album);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
            return View(album);
        }

        //
        // GET: /MusicStore/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Album album = db.Albums.Find(id);
            if (album == null)
            {
                return HttpNotFound();
            }
            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);

            // 如何通过Linq构建SelectList
            ViewBag.ArtistId = new SelectList(db.Artists.Where(x => x.Name.StartsWith("A")).ToList(),
                                              "ArtistId", "Name", album.ArtistId);
            ViewBag.ArtistId = db.Artists.
                Where(x => x.Name.StartsWith("B")).AsEnumerable().
                Select(a => new SelectListItem { Value = a.ArtistId.ToString(), Text = a.Name, Selected = (album.ArtistId == a.ArtistId) }).
                ToList();

            #region 如果代码如下写，则在执行的时候会发生错误。因为System.Linq不能使用ToString()方法

            //            ViewBag.ArtistId = db.Artists.
            //                Where(x => x.Name.StartsWith("B")).
            //                Select(a => new SelectListItem { Value = a.ArtistId.ToString(), Text = a.Name, Selected = (album.ArtistId == a.ArtistId) })
            //                .AsEnumerable()
            //                .ToList();

            #endregion

            //建立一个view model
            AlbumViewModel vmodel = new AlbumViewModel
                {
                    Album = album,
                    Genre = album.Genre,
                    Artist = album.Artist
                };
            return View(vmodel);
        }

        //
        // POST: /MusicStore/Edit/5

        #region 第一种编辑方法，暂时不用。
        /*     /// <summary>
        /// 第一种绑定页面的办法。
        /// </summary>
        /// <param name="album"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Album album)
        {
            //其实，可以根据Request方法直接来获得值。（如果你擅长web编程的话）
            var price = decimal.Parse(Request["Price"]);

            #region 第一种方法

            if (ModelState.IsValid)
            {
                //修改状态。
                db.Entry(album).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
            return View(album);

            #endregion

        } */
        #endregion

        //
        // GET: /MusicStore/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Album album = db.Albums.Find(id);
            if (album == null)
            {
                return HttpNotFound();
            }
            return View(album);
        }

        //
        // POST: /MusicStore/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Album album = db.Albums.Find(id);
            db.Albums.Remove(album);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}